/**
 * 招标信息 - 编辑页面
 * @author liuw
 * @date 2019/11/20
 */
define(function () {
    var self,
        app = win.app,
        doc = document,
        layui = win.layui,
        vueData = {
            isAdd: false,
            form: {
                GWAK009:null,
                GWGA013_TOTAL:null,
                GWGAORIU_NAME:null,
                GWGAORIG_NAME:null,
                GWGA003_NAME:null,
                GWGA008_NAME:null
            },
            selectOptions: {
                sys_n_y : app.datas_("sys_n_y"),
                gwga015Options : app.datas_("gwga015"),
                gwak009Options: app.datas_("crm_gwai300_gwak009")
            },
            detailReadOnly:false,
            rules : {
                GWGA001: [
                    {required: true, message: '不可为空', trigger: 'blur'}
                ],
                GWGA002: [
                    {required: true, message: '不可为空', trigger: 'blur'}
                ],
                GWGA003: [
                    {required: true, message: '不可为空', trigger: 'change'}
                ],
                GWGA004: [
                    {required: true, message: '不可为空', trigger: 'change'}
                ],
                GWGA005: [
                    {required: true, message: '不可为空', trigger: 'change'}
                ],
                GWGA006: [
                    {required: true, message: '不可为空', trigger: 'change'}
                ],
                GWGA008: [
                    {required: true, message: '不可为空', trigger: 'change'}
                ],
                GWGA009: [
                    {required: true, message: '不可为空', trigger: 'change'}
                ],
                GWGA010: [
                    {required: true, message: '不可为空', trigger: 'change'}
                ],
                GWGA011: [
                    {required: true, message: '不可为空', trigger: 'blur'},
                    { type: 'number', message: '必须为数字类型'}
                ],
                GWGA012: [
                    {required: true, message: '不可为空', trigger: 'blur'},
                    { type: 'number', message: '必须为数字类型'}
                ],
                GWGA013: [
                    {required: true, message: '不可为空', trigger: 'blur'},
                    { type: 'number', message: '必须为数字类型'}
                ],
                GWGA015: [
                    {required: false, message: '不可为空', trigger: 'blur'}
                ]
            },
            GWGA015_diabled: true
        },
        listData = [],
        gwgaListData = [],
        gwga_cols = [[
            {type:'checkbox',fixed: 'left'}
            ,{field:"GWGASEQ",width:100,title:"序号"}
            ,{field:"GWGA009",width:100,title:"产品大类",hide:true}
            ,{field:"GWGA009_NAME",width:100,title:"产品大类",event:'openGwga009'}
            ,{field:"GWGA010",width:100,title:"车型类别",hide:true}
            ,{field:"GWGA010_NAME",width:100,title:"车型类别",event:'openGwga010'}
            ,{field:"GWGA011",width:100,title:"吨位",edit:'text'}
            ,{field:"GWGA012",width:100,title:"数量",edit:'text'}
            ,{field:"GWGA013",width:150,title:"预算(万元)",edit:'text'}
        ]],
        cols = [[
            {type:'checkbox',fixed: 'left'}
            ,{field:"GWGB002", width:100, title: "序号"}
            ,{field:"GWGB003", width:100, title: "中标公告发布时间",edit:'date'}
            ,{field:"GWGB004", width:100, title: "中标单位",edit:'text'}
            ,{field:"GWGB006", width:100, title: "中标产品",event:'openGwgb006'}
            ,{field:"GWAHL003", width:100, title: "产品大类"}
            ,{field:"GWAOL003", width:100, title: "车辆类型"}
            ,{field:"GWGB007", width:100, title: "中标单价(万元)",edit:'text'}
            ,{field:"GWGB008", width:100, title: "中标数量",edit:'text'}
            ,{field:"GWGB009", width:100, title: "中标总价(万元)"}
        ]],
        callObj,
        pageVue,
        digit= {
            price: 100,
            amount: 100
        },
        table, form,gwgi001EditTable,gwgi001EditGwgaTable,
        layOpenIndex
    ;

    var Gwai305Edit = app.Module.extend({
        init: function () {
            self = this;
            self._super({
                _tag: 'gwgi001_edit',
                _loadTplsFull: [{
                    dom: 'common_open_window', tpl: 'common/_open_window'
                }]
            }, win);
        },

        initTable: function () {
            layui.use(['table'], function () {
                table = layui.table;
                form = layui.form;
                gwgi001EditTable = table.render({
                    elem: app.getByid(doc, 'gwgi001_edit_table'),
                    id: 'gwgi001_edit_table',
                    height:'240',
                    cols: cols,
                    data: listData,
                    done: function (res, curr, count) {

                    }
                });

            });

            table.on('edit(gwgi001_edit_table)', function (obj) {
                var oldValue = $(this).prev().text();
                if (obj.field === 'GWGB007') { // 中标单价
                    self.onGwgb007Change(obj,oldValue);
                } else if (obj.field === 'GWGB008') {
                    self.onGwgb008Change(obj,oldValue)
                }
                self.numFormatAfterCalulate(obj.data);
                obj.updateOfEdit({
                    GWGB007: obj.data.GWGB007 ,
                    GWGB008: obj.data.GWGB008 ,
                    GWGB009: obj.data.GWGB009
                });
            });
            
            table.on('tool(gwgi001_edit_table)',function (obj) {
                if(obj.event === 'openGwgb006'){ // 中标产品编号

                    self._openTplFull({
                        tag: 'common_open_window',
                        tagData: {
                            config:{
                                method:'q_gwam001',
                                columnList:[
                                    {label:'产品编号',prop:'GWAM001', width: 150},
                                    {label:'产品大类',prop:'GWAHL003', width: 150},
                                    {label:'车辆类型',prop:'GWAOL003', width: 150}
                                ]
                            },
                            cb: function (data) {
                                obj.updateOfEdit({
                                    GWGB006: data.GWAM001,
                                    GWAHL003: data.GWAHL003,
                                    GWAOL003: data.GWAOL003
                                });
                            }
                        },
                        index: 0,
                        openOpts: {
                            title: '选择产品编号',
                            area: ['600px', '465px']
                        }
                    });
                }
            })
        },
        initGwgaTable:function() {
            layui.use(['table'], function () {
                table = layui.table;
                form = layui.form;
                gwgi001EditGwgaTable = table.render({
                    elem: app.getByid(doc, 'gwgi001_edit_gwgaTable'),
                    id: 'gwgi001_edit_gwgaTable',
                    height:'240',
                    cols: gwga_cols,
                    data: gwgaListData,
                    done: function (res, curr, count) {

                    }
                });

            });

            table.on('edit(gwgi001_edit_gwgaTable)', function (obj) {
                var oldValue = $(this).prev().text();
                if (obj.field === 'GWGA011') {
                    self.onGwga011Change(obj,oldValue);
                } else if (obj.field === 'GWGA012') {
                    self.onGwga012Change(obj,oldValue)
                } else if (obj.field === 'GWGA013') {
                    self.onGwga013Change(obj,oldValue)
                }
            });

            table.on('tool(gwgi001_edit_gwgaTable)',function (obj) {
                if(obj.event === 'openGwga009'){
                    self.openGwga009(obj);
                }else if(obj.event === 'openGwga010'){
                    self.openGwga010(obj);
                }
            })
        },

        tableReload: function (listData) {
            self._reloadTable({id: 'gwgi001_edit_table', data: listData});
        },
        gwgaTableReload: function (listData) {
            self._reloadTable({id: 'gwgi001_edit_gwgaTable', data: listData});
        },

        numFormatUtil: function(num ,digit) {
            return math.div(Math.round(math.mul(num,digit)) ,digit);
        },
        numFormatAfterCalulate: function(data) {
            var price = digit.price;
            var amount = digit.amount;
            data.GWGB007 = self.numFormatUtil(data.GWGB007,price);
            data.GWGB009 = self.numFormatUtil(data.GWGB009,amount);
        },

        getDigit:function() {
            app.ajax({
                xurl: 'admin/getDigit',
                async: true,
                cb: function (result) {
                    if(result.ok) {
                        var data = result.data.data;
                        var _digit = {
                            price: Math.pow(10,data.price),
                            amount: Math.pow(10,data.amount),

                        };
                        app.extendUpLow({
                            target: digit,
                            res: _digit,
                            reset: true
                        });
                        console.log(_digit)
                    }else {
                        console.log("获取小数位失败");
                    }
                }
            });
        },

        onGwgb007Change: function(obj,oldValue) {  // 中标单价改变
            let data = obj.data;
            var re = /^-?\d+\.?\d{0,4}$/; //判断是否最多4位小数的数字类型
            if((!re.test(obj.value)) || parseFloat(obj.value) < 0 ){
                data.GWGB007 = oldValue;
                obj.updateOfEdit({
                    GWGB007: oldValue
                });
                app.showWarning("中标单价应为正数且小数位数最多4位");
                return;
            }

            let GWGB007 = data.GWGB007;
            let GWGB008 = data.GWGB008;
            data.GWGB009 = math.mul(GWGB008 , GWGB007);
        },

        onGwgb008Change: function(obj,oldValue) {  // 中标数量改变
            let data = obj.data;
            var re = /^[0-9]*$/; //判断是否正整数
            if((!re.test(obj.value)) || parseFloat(obj.value) < 0 ){
                data.GWGB008 = oldValue;
                obj.updateOfEdit({
                    GWGB008: oldValue
                });
                app.showWarning("数量为应为正整数！");
                return;
            }

            let GWGB007 = data.GWGB007;
            let GWGB008 = data.GWGB008;
            data.GWGB009 = math.mul(GWGB008 , GWGB007);
        },

        onGwga011Change: function(obj,oldValue) {  //
            let data = obj.data;
            var re = /^-?\d+\.?\d{0,4}$/; //判断是否正整数
            if((!re.test(obj.value)) || parseFloat(obj.value) < 0 ){
                data.GWGA011 = oldValue;
                obj.updateOfEdit({
                    GWGA011: oldValue
                });
                app.showWarning("吨位为应为正数！");
            }
        },
        onGwga012Change: function(obj,oldValue) {  //
            let data = obj.data;
            var re = /^[0-9]*$/; //判断是否正整数
            if((!re.test(obj.value)) || parseFloat(obj.value) < 0 ){
                data.GWGA012 = oldValue;
                obj.updateOfEdit({
                    GWGA012: oldValue
                });
                app.showWarning("数为应为正整数！");
            }
        },
        onGwga013Change: function(obj,oldValue) {  // 中标单价改变
            let data = obj.data;
            var re = /^-?\d+\.?\d{0,2}$/; //判断是否最多2位小数的数字类型
            if((!re.test(obj.value)) || parseFloat(obj.value) < 0 ){
                data.GWGA013 = oldValue;
                obj.updateOfEdit({
                    GWGA013: oldValue
                });
                app.showWarning("预算应为正数且小数位数最多2位");
                return;
            }
            vueData.form.GWGA013_TOTAL = self.getGwga013Sum();
        },

        // 计算招标信息明细中的预算总和
        getGwga013Sum: function() {
            let tableData = gwgi001EditGwgaTable.getDatas();
            let sum = 0;
            tableData.forEach(v => {
                let tmp = v.GWGA013;
                if(tmp == null || tmp === "") {
                    tmp = 0;
                }
                sum = math.add(sum,tmp);
            });
            return sum;
        },

        // 产品大类
        openGwga009: function(obj) {
            self._openTplFull({
                tag: 'common_open_window',
                tagData: {
                    config: {
                        method:'q_gwah001',
                        columnList: [
                            {label: '产品分类编号', prop: 'GWAH001', width: '150'},
                            {label: '说明', prop: 'GWAHL003', width: '150'},
                            {label: '助记码', prop: 'GWAHL004', width: '150'}
                        ]
                    },
                    cb: function (data) {
                        obj.updateOfEdit({
                            GWGA009: data.GWAH001,
                            GWGA009_NAME: data.GWAHL003
                        });
                    }
                },
                index: 0,
                openOpts: {
                    title: '选择产品分类',
                    area: ['600px', '465px']
                }
            });
        },
        // 产品系列
        openGwga010: function(obj) {
            self._openTplFull({
                tag: 'common_open_window',
                tagData: {
                    config: {
                        method: 'q_gwam004',
                        searchParam: {
                            GWAM007:obj.data.GWGA009
                        },
                        columnList: [
                            {label: '车型编号', prop: 'GWAM004', width: '150'},
                            {label: '说明', prop: 'GWAOL003', width: '150'},
                            {label: '助记码', prop: 'GWAOL004', width: '150'}
                        ]
                    },
                    cb: function (data) {
                        obj.updateOfEdit({
                            GWGA010: data.GWAM004,
                            GWGA010_NAME: data.GWAOL003
                        });
                    }
                },
                index: 0,
                openOpts: {
                    title: '选择车型类别',
                    area: ['600px', '465px']
                }
            });
        },

        addData: function () {
            let gwgaParamListData = gwgaListData;
            if (gwgaParamListData.length === 0) {
                vueData.form.GWGASEQ = 1;
                gwgaParamListData.push(vueData.form);
            } else {
                gwgaParamListData.addMap(vueData.form);
            }
            app.ajax({
                xurl: 'crm/gwgi001/add',
                xdata: {
                    gwgaTList : gwgaParamListData,
                    gwgbTList: listData
                },
                loading: true,
                toJsonStr: true,
                okmsg: '招标信息增加成功',
                cb: function (result) {
                    if (result.ok) {
                        app.pageModule('gwgi001').reloadTableCurr();
                        self._closeTpl();
                    }
                }
            });
        },

        editData: function () {
            let gwgaParamListData = gwgaListData;
            if (gwgaParamListData.length === 0) {
                vueData.form.GWGASEQ = 1;
                gwgaParamListData.push(vueData.form);
            } else {
                gwgaParamListData.addMap(vueData.form);
            }
            app.ajax({
                xurl: 'crm/gwgi001/edit',
                xdata: {
                    gwgaTList : gwgaParamListData,
                    gwgbTList: listData
                },
                loading: true,
                toJsonStr: true,
                okmsg: '招标信息修改成功',
                cb: function (result) {
                    if (result.ok) {
                        app.pageModule('gwgi001').reloadTableCurr();
                        self._closeTpl();
                    }
                }
            });
        },

        _call: function (tagData) {
            pageVue.$refs.form.resetFields();
            listData = [];
            gwgaListData = [];
            layOpenIndex = tagData.layOpenIndex;
            if (tagData.is_add) {
                vueData.detailReadOnly = false;
                vueData.isAdd = true;
                app.ajax({
                    xurl: 'crm/gwgi001/getAddData',
                    cb: function (result) {
                        if (result.ok) {
                            var resData = result.data.data;
                            app.extendUpLow({
                                target: vueData.form,
                                res: {
                                    GWGAORIU: resData.CURRENT_USER_ID,
                                    GWGAORIU_NAME: resData.CURRENT_USER_NAME,
                                    GWGAORIG: resData.CURRENT_ORG,
                                    GWGAORIG_NAME: resData.CURRENT_ORG_NAME,
                                    GWGAACTI : "Y"
                                },
                                reset: true
                            });
                        }
                    }
                });
                self.tableReload(listData);
                self.gwgaTableReload(gwgaListData);
            } else {
                vueData.isAdd = false;
                callObj = tagData.obj;

                app.extendUpLow({
                    target: vueData.form,
                    res: callObj.data,
                    reset: true
                });
                vueData.detailReadOnly = tagData.detailReadonly;

                app.ajax({
                    xurl: 'crm/gwgi001/getDetailList',
                    xdata: {GWGA001: callObj.data.GWGA001},
                    loading: true,
                    cb: function (result) {
                        if(result.ok) {
                            let data = result.data.data;
                            for (let i = 0; i < data.length; i++) {
                                listData[i] = data[i];
                            }
                            self.tableReload(listData);
                        }
                    }
                });

                app.ajax({
                    xurl: 'crm/gwgi001/getGwgaDetailList',
                    xdata: {GWGA001: callObj.data.GWGA001},
                    loading: true,
                    cb: function (result) {
                        if(result.ok) {
                            let data = result.data.data;
                            for (let i = 0; i < data.length; i++) {
                                gwgaListData[i] = data[i];
                            }
                            self.gwgaTableReload(gwgaListData);
                            vueData.form.GWGA013_TOTAL = self.getGwga013Sum();
                        }
                    }
                });
            }
        },

        // return :
        // true  : date1 < date2
        // false : date1 > date2
        compareDate:function(date1,date2) {
            if(date1 == null || date1 === "" || date2 == null || date2 === ""){
                return true;
            }
            let d1 = new Date(date1);
            let d2 = new Date(date2);
            return d1.getTime() < d2.getTime();
        },
        _ready: function () {
            table = layui.table;
            vueData.form = app.fields_(['GWGA_T'],vueData.form);
            pageVue = new Vue({
                el: '#gwgi001_edit',
                data: vueData,
                methods: {
                    cancle: function () {
                        self._closeTpl();
                    },
                    saveData: function () {
                        this.$refs['form'].validate(function (valid) {
                            if (valid) {
                                if(gwgaListData.length == 0){
                                    app.showWarning("招标产品信息不能为空！");
                                    return;
                                }
                                if (vueData.isAdd) {
                                    self.addData();
                                } else {
                                    self.editData();
                                }
                            }
                        });
                    },

                    // 区域
                    openGwga003: function() {
                        self._openTplFull({
                            tag: 'common_open_window',
                            tagData: {
                                config: {
                                    method:'q_gwad002',
                                    searchParam: {
                                        GWAD001: "3"
                                    },
                                    columnList: [
                                        {label: '区域编号', prop: 'GWAD002', width: '150'},
                                        {label: '区域名称', prop: 'GWADL004', width: '150'},
                                        {label: '助记码', prop: 'GWADL005', width: '150'}
                                    ],
                                },
                                cb: function (data) {
                                    vueData.form.GWGA003 = data.GWAD002;
                                    vueData.form.GWGA003_NAME = data.GWADL004
                                }
                            },
                            index: 0,
                            openOpts: {
                                title: '选择区域',
                                area: ['600px', '465px']
                            }
                        });
                    },
                    // 客户
                    openGwga008: function() {
                        self._openTplFull({
                            tag: 'common_open_window',
                            tagData: {
                                config: {
                                    method:'q_gwak001',
                                    columnList: [
                                        {label: '客户编号', prop: 'GWAK001', width: '150'},
                                        {label: '客户简称', prop: 'GWAKL003', width: '150'},
                                        {label: '客户全称', prop: 'GWAKL004', width: '150'}
                                    ],
                                },
                                cb: function (data) {
                                    vueData.form.GWGA008= data.GWAK001;
                                    vueData.form.GWGA008_NAME = data.GWAKL004;
                                    vueData.form.GWAK009 = data.GWAK009
                                }
                            },
                            index: 0,
                            openOpts: {
                                title: '选择客户',
                                area: ['600px', '465px']
                            }
                        });
                    },

                    addTableData: function () {
                        listData = gwgi001EditTable.getDatas();
                        var count = 0;
                        if (listData.length > 0) {
                            count = parseInt(listData[listData.length - 1].GWGB002);
                        }
                        listData.push({
                            GWGB002: count + 1,
                            GWGB003: '',
                            GWGB004: '',
                            GWGB005: '',
                            GWGB006: '',
                            GWGB007: 0,
                            GWGB008: 0,
                            GWGB009: 0,
                        });
                        self.tableReload(listData);
                    },

                    delTableData: function () {
                        listData = gwgi001EditTable.getDatas();
                        var checkStatus = table.checkStatus('gwgi001_edit_table');
                        if (checkStatus.data.length > 0) {
                            checkStatus.data.forEach(function (v) {
                                listData.removeByMap({
                                    GWGB002: v.GWGB002
                                });
                            });
                            if (listData.length !== 0) {
                                let i = 1;
                                listData.forEach(function (v) {
                                    v.GWGB002 = i;
                                    i++;
                                });
                            }
                            self.tableReload(listData);
                        } else {
                            app.showWarning("至少选择一笔数据进行操作")
                        }
                    },

                    addGwgaTableData: function () {
                        gwgaListData = gwgi001EditGwgaTable.getDatas();
                        var count = 0;
                        if (gwgaListData.length > 0) {
                            count = parseInt(gwgaListData[gwgaListData.length - 1].GWGASEQ);
                        }
                        gwgaListData.push({
                            GWGASEQ: count + 1,
                            GWGA009: '',
                            GWGA010: '',
                            GWGA011: '',
                            GWGA012: '',
                            GWGA013: ''
                        });
                        self.gwgaTableReload(gwgaListData);
                    },

                    delGwgaTableData: function () {
                        gwgaListData = gwgi001EditGwgaTable.getDatas();
                        var checkStatus = table.checkStatus('gwgi001_edit_gwgaTable');
                        if (checkStatus.data.length > 0) {
                            checkStatus.data.forEach(function (v) {
                                gwgaListData.removeByMap({
                                    GWGASEQ: v.GWGASEQ
                                });
                            });
                            if (gwgaListData.length !== 0) {
                                let i = 1;
                                gwgaListData.forEach(function (v) {
                                    v.GWGASEQ = i;
                                    i++;
                                });
                            }
                            self.gwgaTableReload(gwgaListData);
                        } else {
                            app.showWarning("至少选择一笔数据进行操作")
                        }
                    }

                },
                watch: {
                    'form.GWGA004':function(newValue) {
                        if(newValue == null) return;
                        let GWGA005 = vueData.form.GWGA005;
                        if( (!self.compareDate(newValue,GWGA005))) {
                            app.showWarning("公告时间必须小于公告获取结束时间");
                            vueData.form.GWGA004 = null;
                        }
                   },
                    'form.GWGA005':function(newValue) {
                        if(newValue == null) return;
                        let GWGA004 = vueData.form.GWGA004;
                        let GWGA006 = vueData.form.GWGA006;
                        if( !(self.compareDate(GWGA004,newValue) )) {
                            app.showWarning("公告获取结束时间必须大于公告时间");
                            vueData.form.GWGA005 = null;
                        }
                        if( !(self.compareDate(newValue,GWGA006) )) {
                            app.showWarning("公告获取结束时间必须小于开标时间");
                            vueData.form.GWGA005 = null;
                        }
                    },
                    'form.GWGA006':function(newValue) {
                        if(newValue == null) return;
                        let GWGA005 = vueData.form.GWGA005;
                        if( (!self.compareDate(GWGA005,newValue))) {
                            app.showWarning("开标时间必须大于公告获取结束时间");
                            vueData.form.GWGA006 = null;
                        }
                    },
                    'form.GWGA014': function (newValue) {
                        if (newValue === 'N'){
                            vueData.GWGA015_diabled = false;
                            vueData.rules.GWGA015 = new Array( {required: true, message: '不可为空', trigger: 'change'});
                        } else {
                            vueData.GWGA015_diabled = true;
                            vueData.form.GWGA015 = '';
                            vueData.rules.GWGA015 = new Array(
                                {required: false, message: '不可为空', trigger: 'blur'});
                        }
                    }
                },
                created: function () {
                    self._setEleIsReady('gwgi001_edit');
                }
            });
            self.initTable();
            self.initGwgaTable();
        },
        _lazy: function () {
            this._super();
            this.getDigit();
        }
    });

    return new Gwai305Edit();

})
;